/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By zhanglin
* 注意：
* 本软件为zhanglin开发研制
 */
package model

import (
	"shop/global"
)

type IRolesMenus interface {
	InsertRolesMenus() (int64, error)
	DeleteRolesMenus(menuId int64) error
	UpdateRolesMenus() error
	FindRolesMenusList() (interface{}, error)
	SplitPageRolesMenusList(pageIndex int64, pageSize int64) (interface{}, error)
}

/**
	RolesMenus实体对象
 **/
type RolesMenus struct {
	MenuId int64 `json:"menu_id" gorm:"primary_key"` //菜单ID

	RoleId int64 `json:"role_id"` //角色ID
}

func (vo *RolesMenus) InsertRolesMenus() (int64, error) {
	table := global.GDB.Table("roles_menus")
	if err := table.Create(&vo).Error; err != nil {
		return 0, err
	}

	return vo.MenuId, nil
}

func (vo *RolesMenus) DeleteRolesMenus(menuId int64) error {
	table := global.GDB.Table("roles_menus")
	table = table.Where("menu_id = ?", menuId)
	if err := table.Delete(RolesMenus{}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *RolesMenus) UpdateRolesMenus() error {

	table := global.GDB.Table("roles_menus")
	table = table.Where("menu_id = ?", vo.MenuId)
	if err := table.Updates(map[string]interface{}{
		"menu_id": vo.MenuId, "role_id": vo.RoleId}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *RolesMenus) FindRolesMenusList() ([]RolesMenus, error) {
	var lists []RolesMenus
	table := global.GDB.Table("roles_menus")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}

func (vo *RolesMenus) SplitPageRolesMenusList(pageIndex int64, pageSize int64) (interface{}, error) {
	var lists []RolesMenus
	var total int64
	table := global.GDB.Table("roles_menus")
	table = table.Select("  menu_id,   role_id   ")
	if err := table.Count(&total).Error; err != nil {
		return lists, err
	}
	table = table.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}

	m := make(map[string]interface{})
	m["lists"] = lists
	m["total"] = total
	return m, nil
}
